package com.cuput.partybuilding.contact;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.PixelFormat;
import android.graphics.drawable.GradientDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cuput.partybuilding.contact.adapter.ContactGroupItemAdapter;
import com.cuput.partybuilding.contact.bean.Contact;
import com.cuput.partybuilding.contact.comparator.ContactNameCompare;
import com.cuput.partybuilding.contact.presenter.ContactPresenter;
import com.cuput.partybuilding.contact.view.IndexBar;
import com.cuput.partybuilding.publiclibrary.base.BaseActivity;
import com.cuput.partybuilding.publiclibrary.util.Utils;
import com.cuput.partybuilding.publiclibrary.views.TopBarLayout;
import com.github.promeg.pinyinhelper.Pinyin;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import rx.functions.Action1;

/**
 * Created by wei on 2017-05-10.
 * 联系人列表页Activity
 */

public class ContactListActivity extends BaseActivity<ContactPresenter> {
    private TopBarLayout topBarLayout;
    private LinearLayout searchBarLayout;
    private RecyclerView contactRecycleView;
    private ContactGroupItemAdapter contactGroupItemAdapter;
    private TextView searchTv;
    private EditText searchEt;
    private TextView searchCancel;
    private IndexBar indexBar;
    private TextView overlay;
    private OverlayThread overlayThread;
    private Handler handler;

    private ArrayList<Contact> contacts;
    private ArrayList<Contact> searchContacts;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_list);
        initView();
        initListener();

        RxPermissions.getInstance(this)
                .request(Manifest.permission.READ_CONTACTS)
                .subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean granted) {
                if (granted) {
                    contacts = mPresenter.getPhoneContacts();
                    initPinYinData(contacts);
                    Collections.sort(contacts, new ContactNameCompare());
                    contactGroupItemAdapter.setContacts(contacts);
                    contactGroupItemAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    private void initView() {
        topBarLayout = (TopBarLayout) findViewById(R.id.topBar);

        searchBarLayout = (LinearLayout) findViewById(R.id.searchBar);
        GradientDrawable searchBarDraw = (GradientDrawable) searchBarLayout.getBackground();
        searchBarDraw.setColor(getResources().getColor(R.color.colorWhite));

        contactRecycleView = (RecyclerView) findViewById(R.id.contactRecycleView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        contactRecycleView.setLayoutManager(linearLayoutManager);
        contactGroupItemAdapter = new ContactGroupItemAdapter(this, null);
        contactRecycleView.setAdapter(contactGroupItemAdapter);

        searchTv = (TextView) findViewById(R.id.searchTv);
        searchEt = (EditText) findViewById(R.id.searchEt);
        searchCancel = (TextView) findViewById(R.id.searchCancel);

        indexBar = (IndexBar) findViewById(R.id.indexBar);

        LayoutInflater layoutInflater = LayoutInflater.from(this);
        overlay = (TextView) layoutInflater.inflate(R.layout.layout_overlay, null);
        overlay.setVisibility(View.INVISIBLE);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                PixelFormat.TRANSLUCENT);
        WindowManager windowManager =
                (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        windowManager.addView(overlay, lp);

        handler = new Handler();
        overlayThread = new OverlayThread();
    }

    private void initListener() {
        topBarLayout.setTopBarListener(new TopBarLayout.TopBarListener() {
            @Override
            public void setOnLeftClickListener() {
                ContactListActivity.this.finish();
            }

            @Override
            public void setOnRight1ClickListener() {

            }

            @Override
            public void setOnRight2ClickListener() {

            }
        });

        indexBar.setOnTouchingLetterChangedListener(new IndexBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                ArrayList<Contact> tempContacts = searchContacts == null ? contacts : searchContacts;
                for (int i = 0; i < tempContacts.size(); i++) {
                    Contact contact = tempContacts.get(i);
                    String currentIndex = String.valueOf(contact.getPinyin().charAt(0));
                    overlay.setText(s);
                    overlay.setVisibility(View.VISIBLE);
                    handler.removeCallbacks(overlayThread);
                    handler.postDelayed(overlayThread, 1000);
                    if (currentIndex.equals(s)) {
                        contactRecycleView.scrollToPosition(i);
                        break;
                    }
                }
            }
        });

        // 搜索框点击事件
        searchTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int width = searchBarLayout.getWidth();

                // 执行动画
                ViewWrapper searchTvWrapper = new ViewWrapper(searchTv);
                ObjectAnimator.ofInt(searchTvWrapper, "width", width, Utils.dp2px(ContactListActivity.this, 85.0f)).setDuration(70).start();
                ViewWrapper searchEtWrapper = new ViewWrapper(searchEt);
                ObjectAnimator.ofInt(searchEtWrapper, "width", 0, width - Utils.dp2px(ContactListActivity.this, 85.0f)).setDuration(70).start();

                searchEt.requestFocus();
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                inputMethodManager.showSoftInput(searchEt, 0);

                searchCancel.setVisibility(View.VISIBLE);
                searchTv.setClickable(false);
            }
        });

        // 取消按钮的点击事件
        searchCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchEt.setText("");
                searchContacts = null;

                int width = searchBarLayout.getWidth();

                // 执行动画
                ViewWrapper searchTvWrapper = new ViewWrapper(searchTv);
                ObjectAnimator.ofInt(searchTvWrapper, "width", Utils.dp2px(ContactListActivity.this, 85.0f), width).setDuration(70).start();
                ViewWrapper searchEtWrapper = new ViewWrapper(searchEt);
                ObjectAnimator.ofInt(searchEtWrapper, "width", width - Utils.dp2px(ContactListActivity.this, 85.0f), 0).setDuration(70).start();

                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(searchEt.getWindowToken(), 0);

                searchCancel.setVisibility(View.GONE);
                searchTv.setClickable(true);

                // 当取消搜索时，要将数据替换为原来的数据源
                contactGroupItemAdapter.setContacts(contacts);
                contactGroupItemAdapter.notifyDataSetChanged();
            }
        });

        // 键盘监听
        searchEt.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    String searchText = searchEt.getText().toString().trim();
                    doSearch(searchText);
                }
                return false;
            }
        });
    }

    /**
     * 根据昵称设置拼音
     * @param constastBeans
     */
    private void initPinYinData(List<Contact> constastBeans) {
        for(Contact contactRespMsg : constastBeans) {
            contactRespMsg.setPinyin(Utils.getPinYin(contactRespMsg.getContractName()));
        }
    }

    /**
     * 执行搜索动作
     * @param searchText
     */
    private void doSearch(String searchText) {
        searchContacts = mPresenter.findSearch(contacts, searchText);
        contactGroupItemAdapter.setContacts(searchContacts);
        contactGroupItemAdapter.notifyDataSetChanged();

        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(searchEt.getWindowToken(), 0);
    }

    /**
     * 将要执行动画的View包装在此类中
     */
    private class ViewWrapper {
        private View mTarget;

        public ViewWrapper(View target) {
            this.mTarget = target;
        }

        public int getWidth() {
            return mTarget.getLayoutParams().width;
        }

        public void setWidth(int width) {
            mTarget.getLayoutParams().width = width;
            mTarget.requestLayout();
        }
    }

    @Override
    public ContactPresenter getPresenter() {
        return new ContactPresenter(this);
    }

    private class OverlayThread implements Runnable {
        @Override
        public void run() {
            overlay.setVisibility(View.GONE);
        }
    }
}
